package com.second.hand.trading.server.wb;

import com.alibaba.fastjson.JSONObject;
import com.second.hand.trading.server.service.impl.WebSocketServiceImpl;
import com.second.hand.trading.server.wb.pojo.Friend;
import com.second.hand.trading.server.wb.pojo.Result;
import com.second.hand.trading.server.wb.pojo.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@Component
@Slf4j
public class MyWebSocketHandler extends AbstractWebSocketHandler {

    @Autowired
    private WebSocketServiceImpl webSocketService;

    private Map<String,WebSocketSession> sessions1 =new HashMap<>();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("建立ws连接");

//        WsSessionManager.add(session.getId(),session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("发送文本消息");
        // 获得客户端传来的消息
        String payload = message.getPayload();
        log.info("server 接收到消息 " + payload);
        //session.sendMessage(new TextMessage("server 发送给的消息 " + payload + "，发送时间:" + LocalDateTime.now().toString()));

        JSONObject jsonObject = JSONObject.parseObject(payload);
        if(jsonObject.getString("message").equals("初始化")){
            String username = jsonObject.getString("username");
            sessions1.put(username,session);

            username = "\""+username+"\"";
//            String you = jsonObject.getString("you");
//            you = "\""+you+"\"";
            List<Friend> friend = webSocketService.Friend(username);
            Result result = new Result();
            result.setFriend(friend);
            session.sendMessage(new TextMessage(JSONObject.toJSONString(result)));
        }else if(jsonObject.getString("message").equals("")){
            String username = jsonObject.getString("username");
            username = "\""+username+"\"";
            String you = jsonObject.getString("you");
            you = "\""+you+"\"";
            ResultMessage resultMessage = webSocketService.resultMessage(username, you);

            session.sendMessage(new TextMessage(JSONObject.toJSONString(resultMessage)));
        }else {
            String username = jsonObject.getString("username");
            String username1 = "\""+username+"\"";
            String you = jsonObject.getString("you");
            String you1 = "\""+you+"\"";
            String message1 = jsonObject.getString("message");
            message1="\""+message1+"\"";
            webSocketService.messageStorage(username1,you1,message1);

            sessions1.forEach((k,v)->{
                try {
                    if (k.equals(you)){
                        v.sendMessage(new TextMessage(payload));
                    }
                    if (k.equals(username)){
                        v.sendMessage(new TextMessage(payload));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            /*for (WebSocketSession webSocketSession : sessions1) {
                if (webSocketSession.isOpen() && session.equals(webSocketSession)) {
                    webSocketSession.sendMessage(new TextMessage(payload));
                }
            }*/
            //session.sendMessage(new TextMessage(payload));
        }



    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        log.info("发送二进制消息");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("异常处理");
//        WsSessionManager.removeAndClose(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("关闭ws连接");
//        WsSessionManager.removeAndClose(session.getId());
    }
}

